﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Serialization;

namespace ForexTester
{
    public class PerformTrading
    {
        //private static Semaphore semaphoreObject = new Semaphore(5, 5);
        private static bool stop = false;
        public static int currentThreadCounts = 0;

        public static int ThreadCounts { get; set; }
        public static string FilePath { get; set; }

        public static double IterationsPerSeconds { get; set; }

        public static int CurrentEnterance { get; set; }
        public static int CurrentStopLoss { get; set; }
        public static int CurrentTrailingStop { get; set; }
        public static int CurrentTakeProfit { get; set; }

        public static List<Statistic> CurrentStatisticItems { get; set; }




        private static DateTime ParseDate(string p)
        {
            string[] tokens = p.Split('.');
            return new DateTime(int.Parse(tokens[0]), int.Parse(tokens[1]), int.Parse(tokens[2]));
        }

        private static TimeSpan ParseTime(string p)
        {
            string[] tokens = p.Split(':');
            return new TimeSpan(int.Parse(tokens[0]), int.Parse(tokens[1]), 0);
        }

        private static decimal ParseDecimal(string p)
        {
            return decimal.Parse(p.Trim());
        }

        private static int ParseInt(string p)
        {
            return int.Parse(p.Trim());
        }

        private static void OpenDeals_Old(Market marketItem, List<Deal> unOpenDeals, List<Deal> openDeals, decimal currentOpen, int enterance)
        {
            for (int i = 0; i < unOpenDeals.Count; i++)
            {
                if (unOpenDeals[i].DealType == DealType.Buy)
                {
                    if (marketItem.High >= currentOpen + (decimal)enterance / 100)
                    {
                        unOpenDeals[i].State = DealState.Opened;
                        unOpenDeals[i].StartDate = marketItem.Date.Add(marketItem.Time);
                        unOpenDeals[i].StartPrice = currentOpen + (decimal)enterance / 100;

                        openDeals.Add(unOpenDeals[i]);
                        unOpenDeals.Remove(unOpenDeals[i]);
                        i--;
                    }
                }
                else if (unOpenDeals[i].DealType == DealType.Sell)
                {
                    if (marketItem.Low <= currentOpen - (decimal)enterance / 100)
                    {
                        unOpenDeals[i].State = DealState.Opened;
                        unOpenDeals[i].StartDate = marketItem.Date.Add(marketItem.Time);
                        unOpenDeals[i].StartPrice = currentOpen - (decimal)enterance / 100;

                        openDeals.Add(unOpenDeals[i]);
                        unOpenDeals.Remove(unOpenDeals[i]);
                        i--;
                    }
                }
            }
        }
        private static void OpenDeals(Market marketItem, List<Deal> unOpenDeals, List<Deal> openDeals)
        {
            for (int i = 0; i < unOpenDeals.Count; i++)
            {
                if (unOpenDeals[i].DealType == DealType.Buy)
                {
                    if (marketItem.High >= unOpenDeals[i].StartPrice)
                    {
                        unOpenDeals[i].State = DealState.Opened;
                        unOpenDeals[i].StartDate = marketItem.Date.Add(marketItem.Time);

                        openDeals.Add(unOpenDeals[i]);
                        unOpenDeals.Remove(unOpenDeals[i]);
                        i--;
                    }
                }
                else if (unOpenDeals[i].DealType == DealType.Sell)
                {
                    if (marketItem.Low <= unOpenDeals[i].StartPrice)
                    {
                        unOpenDeals[i].State = DealState.Opened;
                        unOpenDeals[i].StartDate = marketItem.Date.Add(marketItem.Time);

                        openDeals.Add(unOpenDeals[i]);
                        unOpenDeals.Remove(unOpenDeals[i]);
                        i--;
                    }
                }
            }
        }



        private static void stopLossDeals(Market marketItem, List<Deal> openDeals, List<Deal> closedDeals)
        {
            for (int i = 0; i < openDeals.Count; i++)
            {
                if (openDeals[i].StopLoss > 0)
                {
                    if (openDeals[i].DealType == DealType.Buy)
                    {
                        openDeals[i].EndPrice = marketItem.Low;
                        if (openDeals[i].ProfitPoints <= -openDeals[i].StopLoss)
                        {
                            openDeals[i].State = DealState.Closed;
                            openDeals[i].EndDate = marketItem.Date.Add(marketItem.Time);
                            openDeals[i].EndPrice = openDeals[i].StartPrice - (decimal)openDeals[i].StopLoss / 100;

                            closedDeals.Add(openDeals[i]);
                            openDeals.Remove(openDeals[i]);
                            i--;
                        }
                    }
                    else if (openDeals[i].DealType == DealType.Sell)
                    {
                        openDeals[i].EndPrice = marketItem.High;
                        if (openDeals[i].ProfitPoints <= -openDeals[i].StopLoss)
                        {
                            openDeals[i].State = DealState.Closed;
                            openDeals[i].EndDate = marketItem.Date.Add(marketItem.Time);
                            openDeals[i].EndPrice = openDeals[i].StartPrice + (decimal)openDeals[i].StopLoss / 100;

                            closedDeals.Add(openDeals[i]);
                            openDeals.Remove(openDeals[i]);
                            i--;
                        }
                    }
                }
            }
        }

        private static void trailingStopDeals(Market marketItem, List<Deal> openDeals, List<Deal> closedDeals)
        {
            for (int i = 0; i < openDeals.Count; i++)
            {
                if (openDeals[i].TrailingStop > 0)
                {
                    if (openDeals[i].DealType == DealType.Buy)
                    {
                        openDeals[i].EndPrice = marketItem.High;
                        if (openDeals[i].PrevouisTrailing != -1 && marketItem.Low <= openDeals[i].PrevouisTrailing)
                        {
                            openDeals[i].State = DealState.Closed;
                            openDeals[i].EndDate = marketItem.Date.Add(marketItem.Time);
                            openDeals[i].EndPrice = openDeals[i].PrevouisTrailing;

                            closedDeals.Add(openDeals[i]);
                            openDeals.Remove(openDeals[i]);
                            i--;
                        }
                        else if ((openDeals[i].ProfitPoints / openDeals[i].TrailingStop) > 1)
                        {
                            openDeals[i].PrevouisTrailing = openDeals[i].StartPrice + ((openDeals[i].ProfitPoints / openDeals[i].TrailingStop) - 1) * ((decimal)openDeals[i].TrailingStop / 100);
                        }
                    }
                    else if (openDeals[i].DealType == DealType.Sell)
                    {
                        openDeals[i].EndPrice = marketItem.Low;
                        if (openDeals[i].PrevouisTrailing != -1 && marketItem.High >= openDeals[i].PrevouisTrailing)
                        {
                            openDeals[i].State = DealState.Closed;
                            openDeals[i].EndDate = marketItem.Date.Add(marketItem.Time);
                            openDeals[i].EndPrice = openDeals[i].PrevouisTrailing;

                            closedDeals.Add(openDeals[i]);
                            openDeals.Remove(openDeals[i]);
                            i--;
                        }
                        else if ((openDeals[i].ProfitPoints / openDeals[i].TrailingStop) > 1)
                        {
                            openDeals[i].PrevouisTrailing = openDeals[i].StartPrice - ((openDeals[i].ProfitPoints / openDeals[i].TrailingStop) - 1) * ((decimal)openDeals[i].TrailingStop / 100);
                        }
                    }
                }
            }
        }

        private static void takeProfitDeals(Market marketItem, List<Deal> openDeals, List<Deal> closedDeals)
        {
            for (int i = 0; i < openDeals.Count; i++)
            {
                if (openDeals[i].TakeProfit > 0)
                {
                    if (openDeals[i].DealType == DealType.Buy)
                    {
                        openDeals[i].EndPrice = marketItem.High;
                        if (openDeals[i].ProfitPoints >= openDeals[i].TakeProfit)
                        {
                            openDeals[i].State = DealState.Closed;
                            openDeals[i].EndDate = marketItem.Date.Add(marketItem.Time);
                            openDeals[i].EndPrice = openDeals[i].StartPrice + (decimal)openDeals[i].TakeProfit / 100;


                            closedDeals.Add(openDeals[i]);
                            openDeals.Remove(openDeals[i]);
                            i--;
                        }
                    }
                    else if (openDeals[i].DealType == DealType.Sell)
                    {
                        openDeals[i].EndPrice = marketItem.Low;
                        if (openDeals[i].ProfitPoints >= openDeals[i].TakeProfit)
                        {
                            openDeals[i].State = DealState.Closed;
                            openDeals[i].EndDate = marketItem.Date.Add(marketItem.Time);
                            openDeals[i].EndPrice = openDeals[i].StartPrice - (decimal)openDeals[i].TakeProfit / 100;


                            closedDeals.Add(openDeals[i]);
                            openDeals.Remove(openDeals[i]);
                            i--;
                        }
                    }
                }
            }
        }

        private static void setEndPrice(Market marketItem, List<Deal> openDeals)
        {
            for (int i = 0; i < openDeals.Count; i++)
            {
                openDeals[i].EndPrice = marketItem.Close;
            }
        }


        private static void addToStatisticItems(Statistic item)
        {
            lock (PerformTrading.CurrentStatisticItems)
            {
                PerformTrading.CurrentStatisticItems.Add(item);
            }
        }
        private static void truncateStatisticItems()
        {
            lock (PerformTrading.CurrentStatisticItems)
            {
                CurrentStatisticItems.RemoveAll(i => i == null);
                CurrentStatisticItems = CurrentStatisticItems.Where(i => (i.TakeProfit > 0 || i.TrailingStop > 0)).OrderByDescending(i => i.ActualProfit).Take(100).ToList();
            }
        }


        public static List<Market> ReadFile(string filePath)
        {
            string[] lines = System.IO.File.ReadAllLines(filePath);
            List<Market> items = new List<Market>();
            for (int i = 0; i < lines.Length; i++)
            {
                if (lines[i].Trim() != "")
                {
                    Market t = new Market();
                    string[] tokens = lines[i].Split(',');
                    t.ItemNumber = i + 1;
                    t.Date = ParseDate(tokens[0]);
                    t.Time = ParseTime(tokens[1]);
                    t.DayOfWeek = t.Date.DayOfWeek.ToString();
                    t.Open = ParseDecimal(tokens[2]);
                    t.High = ParseDecimal(tokens[3]);
                    t.Low = ParseDecimal(tokens[4]);
                    t.Close = ParseDecimal(tokens[5]);
                    t.Volume = ParseInt(tokens[6]);
                    t.Direction = t.Open > t.Close ? "-" : "+";
                    items.Add(t);
                }

            }
            items = items.OrderBy(i => i.Date).ThenBy(i => i.Time).ToList();
            return items;
        }

        public static List<Deal> Analyze_Old(List<Market> marketItems, int enterance, int profit, int loss, int trailingstop, int quantity, decimal spread)
        {
            DateTime prevoisDate = DateTime.Now;
            //List<Deal> allDeals = new List<Deal>();
            List<Deal> unOpenDeals = new List<Deal>();
            List<Deal> openedDeals = new List<Deal>();
            List<Deal> closedDeals = new List<Deal>();
            Deal buyDeal = new Deal();
            Deal sellDeal = new Deal();
            decimal currentOpen = 0;
            for (int i = 0; i < marketItems.Count; i++)
            {
                if (marketItems[i].Date != prevoisDate)
                {
                    //remove unopened (future deals) from prevois date
                    unOpenDeals.Clear();

                    //make future buy deal 
                    buyDeal = new Deal()
                    {
                        DealType = DealType.Buy,
                        Quantity = quantity,
                        Spread = spread,
                        StopLoss = loss,
                        TrailingStop = trailingstop,
                        TakeProfit = profit,
                        State = DealState.Unopened
                    };
                    //make future sell deal 
                    sellDeal = new Deal()
                    {
                        DealType = DealType.Sell,
                        Quantity = quantity,
                        Spread = spread,
                        StopLoss = loss,
                        TrailingStop = trailingstop,
                        TakeProfit = profit,
                        State = DealState.Unopened
                    };
                    unOpenDeals.Add(buyDeal);
                    unOpenDeals.Add(sellDeal);
                    //set open price (used for enterance points)
                    currentOpen = marketItems[i].Open;
                    //set satrt date
                    prevoisDate = marketItems[i].Date;
                }
                OpenDeals_Old(marketItems[i], unOpenDeals, openedDeals, currentOpen, enterance);
                stopLossDeals(marketItems[i], openedDeals, closedDeals);
                trailingStopDeals(marketItems[i], openedDeals, closedDeals);
                takeProfitDeals(marketItems[i], openedDeals, closedDeals);
                if (i == marketItems.Count - 1)
                {
                    setEndPrice(marketItems[i], openedDeals);
                }
            }

            //remove unopened (future deals) from prevois date
            //unOpenDeals.Clear();
            closedDeals.AddRange(openedDeals);
            return closedDeals;
        }

        public static List<Deal> Analyze(List<Market> marketItems, decimal startBuyPrice, decimal startSellPrice, int buyIncreasepoints, int sellDecreasePoints, int profit, int loss, int trailingstop, int quantity, decimal spread)
        {
            var unOpenDeals = new List<Deal>();
            var openedDeals = new List<Deal>();
            var closedDeals = new List<Deal>();

            var currentBuyPrice=startBuyPrice;
            var currentSellPrice=startSellPrice;
            for (int i = 0; i < marketItems.Count; i++)
            {
                while (marketItems[i].High>currentBuyPrice)
                {
                    currentBuyPrice += (decimal)buyIncreasepoints / 100;
                    var buyDeal = new Deal()
                        {
                            DealType = DealType.Buy,
                            Quantity = quantity,
                            Spread = spread,
                            StopLoss = loss,
                            TrailingStop = trailingstop,
                            TakeProfit = profit,
                            State = DealState.Unopened,
                            StartPrice = startBuyPrice
                        };
                    unOpenDeals.Add(buyDeal);
                }
                while (marketItems[i].Low < currentSellPrice)
                {
                    currentSellPrice -= (decimal)sellDecreasePoints / 100;
                    var sellDeal = new Deal()
                    {
                        DealType = DealType.Sell,
                        Quantity = quantity,
                        Spread = spread,
                        StopLoss = loss,
                        TrailingStop = trailingstop,
                        TakeProfit = profit,
                        State = DealState.Unopened,
                        StartPrice = startSellPrice
                    };
                    unOpenDeals.Add(sellDeal);
                }
                OpenDeals(marketItems[i], unOpenDeals, openedDeals);
                stopLossDeals(marketItems[i], openedDeals, closedDeals);
                trailingStopDeals(marketItems[i], openedDeals, closedDeals);
                takeProfitDeals(marketItems[i], openedDeals, closedDeals);
                if (i == marketItems.Count - 1)
                {
                    setEndPrice(marketItems[i], openedDeals);
                }
            }

            closedDeals.AddRange(openedDeals);
            return closedDeals;
        }

        private static void ThreadAnalysis_Old(object obj)
        {
            try
            {
                lock (PerformTrading.CurrentStatisticItems)
                {
                    currentThreadCounts++;
                }
                //semaphoreObject.WaitOne();
                var parameters = (List<object>)obj;
                var markeItems = (List<Market>)parameters[0];
                var enterance = (int)parameters[1];
                var stopLoss = (int)parameters[2];
                var trailingStop = (int)parameters[3];
                var takeProfit = (int)parameters[4];
                var quantity = (int)parameters[5];
                var spread = (decimal)parameters[6];

                var deals = PerformTrading.Analyze_Old(markeItems,enterance, takeProfit, stopLoss, trailingStop, quantity, spread);
                DateTime maxDate = DateTime.MinValue;
                DateTime minDate = DateTime.MaxValue;
                decimal sum = 0;

                for (int i = 0; i < deals.Count; i++)
                {
                    maxDate = deals[i].EndDate > maxDate ? deals[i].EndDate : maxDate;
                    minDate = deals[i].StartDate < minDate ? deals[i].StartDate : minDate;
                    sum += deals[i].ActualProfit;
                }
                //buy
                var statistic = new Statistic()
                {
                    Period = (maxDate - minDate).ToString(),
                    DealsCount = deals.Count,
                    Enterance = enterance,
                    StopLoss = stopLoss,
                    TrailingStop = trailingStop,
                    TakeProfit = takeProfit,
                    ActualProfit = sum
                };
                PerformTrading.addToStatisticItems(statistic);
                //semaphoreObject.Release();
                lock (PerformTrading.CurrentStatisticItems)
                {
                    currentThreadCounts--;
                }
            }
            catch (Exception er)
            {
                MessageBox.Show(er.ToString());
            }
        }

        private static void ThreadAnalysis(object obj)
        {
            try
            {
                lock (PerformTrading.CurrentStatisticItems)
                {
                    currentThreadCounts++;
                }
                //semaphoreObject.WaitOne();
                var parameters = (List<object>)obj;
                var markeItems = (List<Market>)parameters[0];
                var enterance=(int)parameters[1];
                var stopLoss = (int)parameters[2];
                var trailingStop = (int)parameters[3];
                var takeProfit = (int)parameters[4];
                var quantity = (int)parameters[5];
                var spread = (decimal)parameters[6];
                var buyStartPrice = (decimal)parameters[7];
                var sellStartPrice=(decimal)parameters[8];
                var increase=(int)parameters[9];
                var decrease=(int)parameters[10];

                var deals = PerformTrading.Analyze(markeItems, buyStartPrice, sellStartPrice,increase,decrease, takeProfit, stopLoss, trailingStop, quantity, spread);
                DateTime maxDate = DateTime.MinValue;
                DateTime minDate = DateTime.MaxValue;
                decimal sum = 0;

                for (int i = 0; i < deals.Count; i++)
                {
                    maxDate = deals[i].EndDate > maxDate ? deals[i].EndDate : maxDate;
                    minDate = deals[i].StartDate < minDate ? deals[i].StartDate : minDate;
                    sum += deals[i].ActualProfit;
                }
                //buy
                var statistic = new Statistic()
                {
                    Period = (maxDate - minDate).ToString(),
                    DealsCount = deals.Count,
                    Enterance = enterance,
                    StopLoss = stopLoss,
                    TrailingStop = trailingStop,
                    TakeProfit = takeProfit,
                    ActualProfit = sum
                };
                PerformTrading.addToStatisticItems(statistic);
                //semaphoreObject.Release();
                lock (PerformTrading.CurrentStatisticItems)
                {
                    currentThreadCounts--;
                }
            }
            catch (Exception er)
            {
                MessageBox.Show(er.ToString());
            }
        }

        public static void StartComplexAnalysis_Old(List<Market> markeItems, int quantity, decimal spread)
        {
            stop = false;
            DateTime analysisStartTime = DateTime.Now;
            double iterationNumber = 0;
            ThreadCounts = ThreadCounts < 0 ? 1 : ThreadCounts;
            //semaphoreObject.Dispose();
            //semaphoreObject.Close();
            //semaphoreObject = new Semaphore(ThreadCounts, ThreadCounts);
            CurrentStatisticItems = new List<Statistic>();
            var dummy = new Statistic();
            try
            {
                if (File.Exists(PerformTrading.FilePath))
                {
                    using (FileStream file = new FileStream(PerformTrading.FilePath, FileMode.Open))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(List<Statistic>));
                        CurrentStatisticItems = (List<Statistic>)serializer.Deserialize(file);
                        CurrentStatisticItems.RemoveAll(i => i == null);
                        dummy = CurrentStatisticItems.OrderByDescending(i => i.Enterance).ThenByDescending(i => i.StopLoss)
                            .ThenByDescending(i => i.TrailingStop).ThenByDescending(i => i.TakeProfit).First();
                    }
                }
            }
            catch (Exception er)
            {

            }
            for (CurrentEnterance = 0; CurrentEnterance <= 5000; CurrentEnterance += 50)
            {
                if (CurrentEnterance < dummy.Enterance)
                {
                    CurrentEnterance = dummy.Enterance;
                }
                for (CurrentStopLoss = 0; CurrentStopLoss <= 5000; CurrentStopLoss += 50)
                {
                    if (CurrentEnterance == dummy.Enterance && CurrentStopLoss < dummy.StopLoss)
                    {
                        CurrentStopLoss = dummy.StopLoss;
                    }
                    for (CurrentTrailingStop = 0; CurrentTrailingStop <= 5000; CurrentTrailingStop += 50)
                    {
                        if (CurrentEnterance == dummy.Enterance && CurrentStopLoss == dummy.StopLoss && CurrentTrailingStop < dummy.TrailingStop)
                        {
                            CurrentTrailingStop = dummy.TrailingStop;
                        }
                        for (CurrentTakeProfit = 0; CurrentTakeProfit <= 5000; CurrentTakeProfit += 50)
                        {
                            while (currentThreadCounts > ThreadCounts)
                            {
                                Thread.Sleep(10);
                            }
                            iterationNumber++;
                            IterationsPerSeconds = iterationNumber / (DateTime.Now - analysisStartTime).TotalSeconds;
                            if (stop)
                            {
                                return;
                            }

                            if (CurrentEnterance == dummy.Enterance && CurrentStopLoss == dummy.StopLoss && CurrentTrailingStop == dummy.TrailingStop && CurrentTakeProfit < dummy.TakeProfit)
                            {
                                CurrentTakeProfit = dummy.TakeProfit;
                            }
                            if (CurrentTakeProfit == 0)
                            {
                                if (File.Exists(PerformTrading.FilePath))
                                {
                                    File.Copy(PerformTrading.FilePath, PerformTrading.FilePath + ".bak", true);
                                }

                                using (FileStream file = new FileStream(PerformTrading.FilePath, FileMode.Create))
                                {
                                    XmlSerializer serializer = new XmlSerializer(typeof(List<Statistic>));
                                    serializer.Serialize(file, CurrentStatisticItems);
                                }
                                PerformTrading.truncateStatisticItems();
                            }


                            var parameters = new List<object>();
                            parameters.Add(markeItems);
                            parameters.Add(CurrentEnterance);
                            parameters.Add(CurrentStopLoss);
                            parameters.Add(CurrentTrailingStop);
                            parameters.Add(CurrentTakeProfit);
                            parameters.Add(quantity);
                            parameters.Add(spread);
                            Thread t = new Thread(PerformTrading.ThreadAnalysis_Old);
                            t.IsBackground = true;
                            t.Start(parameters);
                        }
                    }
                }
            }
        }

        public static void StartComplexAnalysis(List<Market> markeItems, int quantity, decimal spread,decimal buyStart,decimal SellStart,int increase,int decrease)
        {
            stop = false;
            DateTime analysisStartTime = DateTime.Now;
            double iterationNumber = 0;
            ThreadCounts = ThreadCounts < 0 ? 1 : ThreadCounts;
            //semaphoreObject.Dispose();
            //semaphoreObject.Close();
            //semaphoreObject = new Semaphore(ThreadCounts, ThreadCounts);
            CurrentStatisticItems = new List<Statistic>();
            var dummy = new Statistic();
            try
            {
                if (File.Exists(PerformTrading.FilePath))
                {
                    using (FileStream file = new FileStream(PerformTrading.FilePath, FileMode.Open))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(List<Statistic>));
                        CurrentStatisticItems = (List<Statistic>)serializer.Deserialize(file);
                        CurrentStatisticItems.RemoveAll(i => i == null);
                        dummy = CurrentStatisticItems.OrderByDescending(i => i.Enterance).ThenByDescending(i => i.StopLoss)
                            .ThenByDescending(i => i.TrailingStop).ThenByDescending(i => i.TakeProfit).First();
                    }
                }
            }
            catch (Exception er)
            {

            }
            for (CurrentEnterance = 0; CurrentEnterance <= 5000; CurrentEnterance += 50)
            {
                if (CurrentEnterance < dummy.Enterance)
                {
                    CurrentEnterance = dummy.Enterance;
                }
                for (CurrentStopLoss = 0; CurrentStopLoss <= 5000; CurrentStopLoss += 50)
                {
                    if (CurrentEnterance == dummy.Enterance && CurrentStopLoss < dummy.StopLoss)
                    {
                        CurrentStopLoss = dummy.StopLoss;
                    }
                    for (CurrentTrailingStop = 0; CurrentTrailingStop <= 5000; CurrentTrailingStop += 50)
                    {
                        if (CurrentEnterance == dummy.Enterance && CurrentStopLoss == dummy.StopLoss && CurrentTrailingStop < dummy.TrailingStop)
                        {
                            CurrentTrailingStop = dummy.TrailingStop;
                        }
                        for (CurrentTakeProfit = 0; CurrentTakeProfit <= 5000; CurrentTakeProfit += 50)
                        {
                            while (currentThreadCounts > ThreadCounts)
                            {
                                Thread.Sleep(10);
                            }
                            iterationNumber++;
                            IterationsPerSeconds = iterationNumber / (DateTime.Now - analysisStartTime).TotalSeconds;
                            if (stop)
                            {
                                return;
                            }

                            if (CurrentEnterance == dummy.Enterance && CurrentStopLoss == dummy.StopLoss && CurrentTrailingStop == dummy.TrailingStop && CurrentTakeProfit < dummy.TakeProfit)
                            {
                                CurrentTakeProfit = dummy.TakeProfit;
                            }
                            if (CurrentTakeProfit == 0)
                            {
                                if (File.Exists(PerformTrading.FilePath))
                                {
                                    File.Copy(PerformTrading.FilePath, PerformTrading.FilePath + ".bak", true);
                                }

                                using (FileStream file = new FileStream(PerformTrading.FilePath, FileMode.Create))
                                {
                                    XmlSerializer serializer = new XmlSerializer(typeof(List<Statistic>));
                                    serializer.Serialize(file, CurrentStatisticItems);
                                }
                                PerformTrading.truncateStatisticItems();
                            }


                            var parameters = new List<object>();
                            parameters.Add(markeItems);
                            parameters.Add(CurrentEnterance);
                            parameters.Add(CurrentStopLoss);
                            parameters.Add(CurrentTrailingStop);
                            parameters.Add(CurrentTakeProfit);
                            parameters.Add(quantity);
                            parameters.Add(spread);
                            parameters.Add(buyStart);
                            parameters.Add(SellStart);
                            parameters.Add(increase);
                            parameters.Add(decrease);
                            Thread t = new Thread(PerformTrading.ThreadAnalysis);
                            t.IsBackground = true;
                            t.Start(parameters);
                        }
                    }
                }
            }
        }

        public static void StopComplexAnalysis()
        {
            stop = true;
        }

    }
}
